package com.demo.mantis.web;

import java.util.Random;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.demo.mantis.model.Student;

import cn.techarts.dragonfly.web.WebContext;
import cn.techarts.dragonfly.web.rest.Post;
import cn.techarts.dragonfly.web.rest.Get;
import cn.techarts.dragonfly.web.rest.Restful;
import com.demo.mantis.service.StudentService;

@Singleton
@Restful
public class StudentWebService {

	@Inject
	private StudentService service;

	// @Post("/student")
	// public Student registerStudent(WebContext arg) {
	// String name = arg.get("name");
	// String gender = arg.get("gender");
	// Student student = new Student();
	// student.setName(name);
	// student.setGender(gender);
	// //模拟生成一个学生ID
	// student.setId(new Random().nextInt());
	// return student;
	// }

	@Post("/student")
	public Student registerStudent(WebContext arg) {
		String name = arg.get("name");
		String gender = arg.get("gender");
		var result = service.register(name, gender);
		if (result == null) {
			arg.error(-5, "The student name is required");
		}
		return result;
	}

	@Get("/Student/{id}")
	public Student getStudent(WebContext arg) {
		var id = arg.intAt(0);
		var result = service.findStudent(id);
		if (result == null) {
			arg.error(-9, "The student does not exist");
		}
		return result;
	}

	@Get(value = "/login/{user}/{password}", mandatory = false)
	public String login(WebContext arg) {
		var user = arg.at(0);
		var password = arg.at(1);
		return arg.getToken(user);
	}

}
